<?php

namespace app\services\care;

use app\dao\care\ServiceCouponDao;
use app\model\activity\coupon\StoreCouponIssueUser;
use app\model\activity\coupon\StoreCouponUser;
use app\model\care\ServiceItem;
use app\services\activity\coupon\StoreCouponIssueUserServices;
use app\services\activity\coupon\StoreCouponUserServices;
use app\services\BaseServices;
use app\services\user\member\MemberRightServices;
use app\services\user\UserServices;
use crmeb\exceptions\ApiException;
use think\exception\ValidateException;

/**
 * 按摩优惠券表
 * @author lan
 * @version 2024-03-22
 */
class ServiceCouponServices extends BaseServices
{
    public function __construct(ServiceCouponDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 优惠券列表
     * @param int $uid
     * @param array $where
     * @return array
     * @throws \ReflectionException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(int $uid, array $where = [])
    {
        // 获取用户已领取过的优惠券
        [$page,$limit] = $this->getPageValue();
        $list = $this->dao->getList($where,$page,$limit,$uid);
        foreach ($list as &$item){
            $item['is_use'] = count($item['used']);
            $item['coupon_price'] = floatval($item['coupon_price']);
            $item['use_min_price'] = floatval($item['use_min_price']);
            $item['start_use_time'] = $item['start_use_time'] > 0 ? date('Y/m/d', $item['start_use_time']) : 0;
            $item['end_use_time'] = $item['start_use_time'] > 0 ? date('Y/m/d', $item['end_use_time']) : 0;
        }
        if($list){
            $max_price = max(array_column($list,'coupon_price'));
        }else{
            $max_price = 0;
        }
        if(isset($where['item_id'])&&$where['item_id']){
            $price = ServiceItem::where('id',$where['item_id'])->value('price');
            $arch_price = bcsub((string)$price,(string)$max_price,2);
            if($arch_price <= 0){
                $arch_price = 0;
            }
        }else{
            $arch_price = 0;
        }
        $count = $this->dao->count($where);
        return compact('list','count','arch_price');
    }

    /**
     * 领取优惠券
     * @param int $id
     * @param array $user
     * @param bool $is_receive
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function receive(int $id,array $user,bool $is_receive = true)
    {
        $issueCouponInfo = $this->dao->getInfo($id);
        $uid = $user['uid'];
        if(!$issueCouponInfo){
            throw new ValidateException('领取的优惠劵已领完或已过期');
        }
        /** @var MemberRightServices $memberRightService */
        $memberRightService = app()->make(MemberRightServices::class);
        if ($issueCouponInfo['receive_type'] == 4 && (!$user['is_money_level'] || !$memberRightService->getMemberRightStatus("coupon"))) {
            if (!$user['is_money_level']) {
                throw new ApiException(400097);
            }
        }
        /** @var StoreCouponIssueUserServices $issueUserService */
        $issueUserService = app()->make(StoreCouponIssueUserServices::class);
        /** @var StoreCouponUserServices $couponUserService */
        $couponUserService = app()->make(StoreCouponUserServices::class);
        $this->transaction(function () use ($issueUserService, $uid, $id, $couponUserService, $issueCouponInfo,$is_receive) {
            $issueUserService->save(['uid' => $uid, 'issue_coupon_id' => $id, 'add_time' => time()]);
            $couponUserService->addUserCoupon($uid, $issueCouponInfo, $is_receive ? 'get' : 'send');
            if ($issueCouponInfo['total_count'] > 0 && $is_receive) {
                $issueCouponInfo['remain_count'] -= 1;
                $issueCouponInfo->save();
            }
        });
    }

    /**
     * 获取用户已领取的优惠券
     * @param int $uid
     * @param $types
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserCouponList(int $uid, $types)
    {
        /** @var UserServices $userServices */
        $userServices = app()->make(UserServices::class);
        if(!$userServices->getUserInfo($uid)){
            throw new ValidateException('缺少参数');
        }
        /** @var StoreCouponUserServices $storeCouponUser */
        $storeCouponUser = app()->make(StoreCouponUserServices::class);
        return $storeCouponUser->getUserCounpon($uid,$types);
    }

    /**
     * 获取金额可用优惠券
     * @param int $uid
     * @param array $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPriceUserCoupon(int $uid,array $where)
    {
        $userCoupons = $this->dao->getUserAllCoupon($uid);
        $list = [];
        foreach ($userCoupons as $coupon){
            if($coupon['item_ids']){
                if(!in_array((string)$where['item_id'],explode(',',$coupon['item_ids']))){
                    continue;
                }
            }
            if($coupon && $coupon['use_min_price'] <= $where['use_min_price']){
                $coupon['start_time'] = $coupon['start_time'] ? date('Y/m/d',$coupon['start_time']) : date('Y/m/d',$coupon['add_time']);
                $coupon['add_time'] = date('Y/m/d', $coupon['add_time']);
                $coupon['end_time'] = date('Y/m/d', $coupon['end_time']);
                $coupon['start_use_time'] = $coupon['start_use_time'] > 0 ? date('Y/m/d', $coupon['start_use_time']) : 0;
                $coupon['end_use_time'] = $coupon['start_use_time'] > 0 ? date('Y/m/d', $coupon['end_use_time']) : 0;
                $coupon['title'] = $coupon['coupon_title'];
                $coupon['type'] = $coupon['applicable_type'];
                $coupon['use_min_price'] = floatval($coupon['use_min_price']);
                $coupon['coupon_price'] = floatval($coupon['coupon_price']);
                $list[] = $coupon;
            }
        }
        return $list;
    }

    /**
     * 获取用户可领和服务可用优惠券
     * @param int $uid
     * @param array $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserItemCouponList(int $uid, array $where)
    {
        // 获取用户已领取过的优惠券
        $cids = StoreCouponUser::alias('u')->join('store_coupon_issue i','i.id=u.cid','left')->where(['u.uid'=>$uid,'i.receive_type'=>1])->group('u.cid')->column('u.cid');
        $coupon_count = count($cids);
        $where['cids'] = $cids;
        $list = $this->dao->getUserItemCouponList($where);
        foreach ($list as $key => &$item){
            $item['coupon_price'] = floatval($item['coupon_price']);
            if($item['item_ids']){
                if(!in_array((string)$where['item_id'],explode(',',$item['item_ids']))){
                    array_splice($list,$key,1);
                }
            }
        }
        if($list){
            $max_price = max(array_column($list,'coupon_price'));
        }else{
            $max_price = 0;
        }
        if(isset($where['item_id'])&&$where['item_id']){
            $price = ServiceItem::where('id',$where['item_id'])->value('price');
            $arch_price = bcsub((string)$price,(string)$max_price,2);
            if($arch_price <= 0){
                $arch_price = 0;
            }
        }else{
            $arch_price = 0;
        }
        return compact('list','arch_price','coupon_count');
    }

}